import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI, registerAPI, sendEmailCode, verifyEmailCode, getUserInfoAPI } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

interface UserInfo {
  id: number
  username: string
  email: string
  role: string
  real_name?: string
  phone?: string
  organization?: string
  department?: string
  research_direction?: string[]
  avatar?: string
  status?: string
}

interface ApiResponse<T = any> {
  code: number
  message?: string
  data: T
}

interface LoginResponseData {
  token: string
  refresh_token: string
  user: UserInfo
}

interface RegisterResponseData {
  username: string
  email: string
  role: string
  status: string
}

export const useAuthStore = defineStore('auth', () => {
  // 从localStorage恢复状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')

  const login = async (Email: string, Password: string) => {
    try {
      const response = await loginAPI({
        Email,
        Password
      })

      if (response.code === 200) {
        token.value = response.data.token
        refreshToken.value = response.data.refresh_token
        userInfo.value = response.data.user
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('refreshToken', response.data.refresh_token)
        return { success: true, data: response.data }
      } else {
        return {
          success: false,
          message: response.message || '登录失败'
        }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return {
        success: false,
        message: '网络错误，请稍后重试'
      }
    }
  }

  const register = async (data: {
    username: string
    email: string
    role: string
    password: string
    phone?: string
    real_name: string
    organization?: string
    department?: string
    research_direction?: string[]
  }) => {
    try {
      // 处理角色映射（前端mentor对应后端tutor）
      const requestData = {
        ...data,
        role: data.role === 'mentor' ? 'tutor' : data.role
      }

      const response = await registerAPI(requestData)

      if (response.code === 200) {
        return {
          success: true,
          data: response.data
        }
      } else {
        return {
          success: false,
          message: response.message || '注册失败'
        }
      }
    } catch (error) {
      console.error('注册失败:', error)
      return {
        success: false,
        message: '网络错误，请稍后重试'
      }
    }
  }

  const sendEmailCodeAction = async (email: string) => {
    try {
      const response = await sendEmailCode(email)
      return response.data?.success || false
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  }

  const verifyEmailCodeAction = async (email: string, code: string) => {
    try {
      const response = await verifyEmailCode(email, code)
      return (response as any).data?.success || false
    } catch (error) {
      console.error('验证码验证失败:', error)
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    refreshToken.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('admin_token')
  }

  // 供组件直接调用的简洁别名
  const clearToken = () => {
    logout()
  }

  // 初始化用户信息（从localStorage恢复）
  const initializeUserInfo = async () => {
    if (token.value && !userInfo.value) {
      try {
        const response: any = await getUserInfoAPI()
        if (response && response.code === 200 && response.data) {
          userInfo.value = response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，清除token
        logout()
      }
    }
  }

  return {
    token,
    userInfo,
    refreshToken,
    login,
    register,
    sendEmailCode: sendEmailCodeAction,
    verifyEmailCode: verifyEmailCodeAction,
    logout,
    clearToken,
    initializeUserInfo
  }
}, {
  // 配置pinia持久化
  persist: true
})